package bintree.heap.leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
 * 优先级队列解决k个和最小的数字对问题
 * https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums/
 * @author yuisama
 * @date 2022/01/07 14:36
 **/
public class Num373 {
    class Pair implements Comparable<Pair> {
        int val1;
        int val2;
        public Pair(int val1, int val2) {
            this.val1 = val1;
            this.val2 = val2;
        }
        @Override
        public int compareTo(Pair o) {
            return (o.val1 + o.val2) - (this.val1 + this.val2);
        }
    }

    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<List<Integer>> ret = new ArrayList<>();
        PriorityQueue<Pair> queue = new PriorityQueue<>();
        for (int i = 0; i < Math.min(k,nums1.length); i++) {
            for (int j = 0; j < Math.min(k,nums2.length); j++) {
                if (queue.size() < k) {
                    queue.offer(new Pair(nums1[i],nums2[j]));
                }else {
                    Pair pair = queue.peek();
                    if (nums1[i] + nums2[j] < (pair.val1 + pair.val2)) {
                        queue.poll();
                        queue.offer(new Pair(nums1[i],nums2[j]));
                    }
                }
            }
        }
        // 注意加队列空的判断，k有可能大于最后结果集数量的
        for (int i = 0; i < k && !(queue.isEmpty()); i++) {
            List<Integer> temp = new ArrayList<>();
            Pair pair = queue.poll();
            temp.add(pair.val1);
            temp.add(pair.val2);
            ret.add(temp);
        }
        return ret;
    }
}